{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Training a Classifier\n",
    "=====================\n",
    "This is it. You have seen how to define neural networks, compute loss and make\n",
    "updates to the weights of the network.\n",
    "Now you might be thinking,\n",
    "What about data?\n",
    "----------------\n",
    "Generally, when you have to deal with image, text, audio or video data,\n",
    "you can use standard python packages that load data into a numpy array.\n",
    "Then you can convert this array into a ``torch.*Tensor``.\n",
    "-  For images, packages such as Pillow, OpenCV are useful\n",
    "-  For audio, packages such as scipy and librosa\n",
    "-  For text, either raw Python or Cython based loading, or NLTK and\n",
    "   SpaCy are useful\n",
    "Specifically for vision, we have created a package called\n",
    "``torchvision``, that has data loaders for common datasets such as\n",
    "Imagenet, CIFAR10, MNIST, etc. and data transformers for images, viz.,\n",
    "``torchvision.datasets`` and ``torch.utils.data.DataLoader``.\n",
    "This provides a huge convenience and avoids writing boilerplate code.\n",
    "For this tutorial, we will use the CIFAR10 dataset.\n",
    "It has the classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’,\n",
    "‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. The images in CIFAR-10 are of\n",
    "size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size.\n",
    ".. figure:: /_static/img/cifar10.png\n",
    "   :alt: cifar10\n",
    "   cifar10\n",
    "Training an image classifier\n",
    "----------------------------\n",
    "We will do the following steps in order:\n",
    "1. Load and normalizing the CIFAR10 training and test datasets using\n",
    "   ``torchvision``\n",
    "2. Define a Convolutional Neural Network\n",
    "3. Define a loss function\n",
    "4. Train the network on the training data\n",
    "5. Test the network on the test data\n",
    "1. Loading and normalizing CIFAR10\n",
    "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
    "Using ``torchvision``, it’s extremely easy to load CIFAR10."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://mirrors.aliyun.com/pypi/simple\n",
      "Requirement already satisfied: tqdm in /home/qiangzibro/anaconda3/envs/pvnet37/lib/python3.7/site-packages (4.19.9)\n"
     ]
    }
   ],
   "source": [
    "!pip install tqdm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torchvision\n",
    "import torchvision.transforms as transforms\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim\n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "You are using: cuda:1\n"
     ]
    }
   ],
   "source": [
    "# Device configuration\n",
    "device = torch.device('cuda:1' if torch.cuda.is_available() else 'cpu')\n",
    "print(\"You are using:\", device)\n",
    "\n",
    "# Hyper parameters\n",
    "num_epochs = 5\n",
    "num_classes = 10\n",
    "batch_size = 25\n",
    "learning_rate = 0.001\n",
    "DATA_PATH = '../../../../../dataset/'\n",
    "transform = transforms.Compose([transforms.ToTensor(),\n",
    "                                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Files already downloaded and verified\n"
     ]
    }
   ],
   "source": [
    "# 训练集\n",
    "\n",
    "train_dataset = torchvision.datasets.CIFAR10(root=DATA_PATH,\n",
    "                                             train=True,\n",
    "                                             transform=transform,\n",
    "                                             download=True)\n",
    "# 测试集\n",
    "test_dataset = torchvision.datasets.CIFAR10(root=DATA_PATH,\n",
    "                                            train=False,\n",
    "                                            transform=transform)\n",
    "\n",
    "# Data loader\n",
    "train_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n",
    "                                           batch_size=batch_size,\n",
    "                                           shuffle=True)\n",
    "\n",
    "test_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n",
    "                                          batch_size=batch_size,\n",
    "                                          shuffle=False)\n",
    "classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Lenet network\n",
    "class Net(nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.conv1 = nn.Conv2d(3, 6, 5) #in_channels, out_channels, kernel_size, stride=1 ...\n",
    "        self.conv2 = nn.Conv2d(6, 16, 5)\n",
    "        self.fc1 = nn.Linear(16 * 5 * 5, 120)\n",
    "        self.fc2 = nn.Linear(120, 84)\n",
    "        self.fc3 = nn.Linear(84, num_classes)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = F.max_pool2d(F.relu(self.conv1(x)), kernel_size=(2, 2))\n",
    "        x = F.max_pool2d(F.relu(self.conv2(x)), kernel_size=(2, 2))\n",
    "\n",
    "        x = x.view(x.size()[0], -1)\n",
    "        x = F.relu(self.fc1(x))\n",
    "        x = F.relu(self.fc2(x))\n",
    "        x = self.fc3(x)\n",
    "        return x\n",
    "\n",
    "\n",
    "model = Net().to(device)\n",
    "# Loss and optimizer\n",
    "criterion = nn.CrossEntropyLoss()\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:49<00:00,  9.95s/it]\n"
     ]
    }
   ],
   "source": [
    "# Train the model\n",
    "total_step = len(train_loader)\n",
    "for epoch in tqdm(range(num_epochs)):\n",
    "    for i, (images, labels) in enumerate(train_loader):\n",
    "        images = images.to(device)\n",
    "        labels = labels.to(device)\n",
    "\n",
    "        # Forward pass\n",
    "        outputs = model(images)\n",
    "        loss = criterion(outputs, labels)\n",
    "\n",
    "        # Backward and optimize\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "#         if (i + 1) % 100 == 0:\n",
    "#             print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'\n",
    "#                   .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Test Accuracy of the model on test images: 60.65 %\n"
     ]
    }
   ],
   "source": [
    "model.eval()  # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)\n",
    "with torch.no_grad():\n",
    "    correct = 0\n",
    "    total = 0\n",
    "    for images, labels in test_loader:\n",
    "        images = images.to(device)\n",
    "        labels = labels.to(device)\n",
    "        outputs = model(images)\n",
    "        _, predicted = torch.max(outputs.data, 1)\n",
    "        total += labels.size(0)\n",
    "        correct += (predicted == labels).sum().item()\n",
    "\n",
    "    print('Test Accuracy of the model on test images: {} %'.format(100 * correct / total))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.save(model.state_dict(), 'model.ckpt')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
